#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
悬浮球控制模块
"""

import os
from PyQt5.QtWidgets import (
    QWidget, QPushButton, QVBoxLayout, QHBoxLayout, 
    QLabel, QMenu, QAction
)
from math import cos, sin, radians
from PyQt5.QtCore import Qt, QPoint, pyqtSignal, QTimer, QPropertyAnimation, QEasingCurve
from PyQt5.QtGui import QIcon, QColor, QPainter, QPixmap, QCursor, QFont
from PyQt5.QtWidgets import QApplication, QLabel

class FloatBallButton(QPushButton):
    """悬浮球按钮类"""
    def __init__(self, parent=None, size=50):
        super().__init__(parent)
        self.setFixedSize(size, size)
        self.setStyleSheet("""
            QPushButton {
                background-color: rgba(70, 130, 180, 180);
                border-radius: 25px;
                border: 2px solid white;
            }
            QPushButton:hover {
                background-color: rgba(70, 130, 180, 220);
            }
            QPushButton:pressed {
                background-color: rgba(70, 130, 180, 250);
            }
        """)
        
        # 设置按钮图标
        self.setIconSize(self.size() * 0.6)
        
    def paintEvent(self, event):
        """自定义绘制事件"""
        super().paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 绘制圆形背景
        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(70, 130, 180, 180))
        painter.drawEllipse(2, 2, self.width() - 4, self.height() - 4)

class FloatBall(QWidget):
    """悬浮球控件类"""
    # 定义信号
    start_recording = pyqtSignal()  # 开始录制信号
    stop_recording = pyqtSignal()   # 停止录制信号
    pause_recording = pyqtSignal()  # 暂停录制信号
    resume_recording = pyqtSignal() # 恢复录制信号
    show_main_window = pyqtSignal() # 显示主窗口信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.is_recording = False
        self.is_paused = False
        self.recording_time = 0  # 录制时间(秒)
        self.animation_timer = None  # 动画计时器
        self.pulse_animation = False  # 是否启用脉冲动画
        self.drag_offset = QPoint()
        self.drag_animation = None  # 拖动动画
        self.hover_animation = False  # 悬停动画状态
        self.orbit_radius = 0  # 环绕球半径
        self.orbit_angle = 0  # 环绕球角度
        self.orbit_buttons = []  # 环绕按钮列表
        self.init_ui()
        self.setup_animation()
        self.setup_drag_behavior()
        self.setup_orbit_buttons()
        
    def init_ui(self):
        """初始化UI"""
        # 设置窗口属性
        self.setWindowFlags(
            Qt.WindowStaysOnTopHint |  # 窗口置顶
            Qt.FramelessWindowHint |   # 无边框
            Qt.Tool                    # 工具窗口，不在任务栏显示
        )
        self.setAttribute(Qt.WA_TranslucentBackground)  # 透明背景
        
        # 设置窗口大小
        self.setFixedSize(80, 80)  # 增大尺寸以容纳时间显示
        
        # 创建主布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 创建悬浮球按钮
        self.float_button = FloatBallButton(self)
        self.float_button.clicked.connect(self.on_float_button_clicked)
        layout.addWidget(self.float_button, 0, Qt.AlignCenter)
        
        # 创建时间标签
        self.time_label = QLabel("00:00")
        self.time_label.setAlignment(Qt.AlignCenter)
        self.time_label.setStyleSheet("""
            QLabel {
                color: white;
                font-size: 12px;
                font-weight: bold;
                background-color: rgba(0, 0, 0, 80);
                border-radius: 8px;
                padding: 2px 6px;
                margin-top: 2px;
            }
        """)
        layout.addWidget(self.time_label)
        
        # 设置悬浮球初始位置和大小
        self.setFixedSize(80, 90)
        self.setWindowOpacity(0.8)
        
        # 设置初始图标
        self.update_button_icon()
        self.update_time_display()
        
        # 鼠标拖动相关变量
        self.dragging = False
        self.offset = QPoint()
        
        # 设置初始位置（屏幕右侧中间）
        self.move_to_default_position()
        
    def setup_animation(self):
        """设置动画效果"""
        self.animation_timer = QTimer(self)
        self.animation_timer.timeout.connect(self.update_animation)
        self.animation_timer.start(50)  # 20 FPS动画
        
        # 初始化动画变量
        self.pulse_radius = 0
        self.pulse_alpha = 0
        self.pulse_growing = True
    
    def update_animation(self):
        """更新动画效果"""
        if self.pulse_animation:
            # 脉冲动画
            if self.pulse_growing:
                self.pulse_radius += 1
                self.pulse_alpha += 5
                if self.pulse_radius >= 10:
                    self.pulse_growing = False
            else:
                self.pulse_radius -= 1
                self.pulse_alpha -= 5
                if self.pulse_radius <= 0:
                    self.pulse_growing = True
        
        if self.hover_animation:
            # 悬停环绕动画
            if self.orbit_radius < 30:
                self.orbit_radius += 1
            self.orbit_angle = (self.orbit_angle + 2) % 360
            
            # 更新按钮位置
            main_center = self.float_button.geometry().center()
            for i, btn in enumerate(self.orbit_buttons):
                angle = radians(self.orbit_angle + i * 180)
                x = main_center.x() + self.orbit_radius * cos(angle) - 15
                y = main_center.y() + self.orbit_radius * sin(angle) - 15
                btn.move(int(x), int(y))
            
        self.update()  # 触发重绘
    
    def update_button_icon(self):
        """更新按钮图标"""
        if self.is_recording:
            if self.is_paused:
                # 暂停状态 - 显示播放图标
                self.float_button.setStyleSheet("""
                    QPushButton {
                        background-color: rgba(70, 130, 180, 180);
                        border-radius: 35px;
                        border: 2px solid white;
                    }
                    QPushButton:hover {
                        background-color: rgba(70, 130, 180, 220);
                    }
                """)
                self.float_button.setText("▶")
                self.float_button.setStyleSheet(self.float_button.styleSheet() + """
                    QPushButton {
                        color: white; 
                        font-size: 24px;
                        font-weight: bold;
                    }
                """)
                self.pulse_animation = False
            else:
                # 录制状态 - 显示停止图标
                self.float_button.setStyleSheet("""
                    QPushButton {
                        background-color: rgba(220, 20, 60, 180);
                        border-radius: 35px;
                        border: 2px solid white;
                    }
                    QPushButton:hover {
                        background-color: rgba(220, 20, 60, 220);
                    }
                """)
                self.float_button.setText("■")
                self.float_button.setStyleSheet(self.float_button.styleSheet() + """
                    QPushButton {
                        color: white; 
                        font-size: 24px;
                        font-weight: bold;
                    }
                """)
                self.pulse_animation = True
        else:
            # 未录制状态 - 显示录制图标
            self.float_button.setStyleSheet("""
                QPushButton {
                    background-color: rgba(70, 130, 180, 180);
                    border-radius: 35px;
                    border: 2px solid white;
                }
                QPushButton:hover {
                    background-color: rgba(70, 130, 180, 220);
                }
            """)
            self.float_button.setText("●")
            self.float_button.setStyleSheet(self.float_button.styleSheet() + """
                QPushButton {
                    color: red; 
                    font-size: 28px;
                    font-weight: bold;
                }
            """)
            self.pulse_animation = False
        
        self.float_button.update()
    
    def update_time_display(self):
        """更新时间显示"""
        if self.is_recording:
            minutes = self.recording_time // 60
            seconds = self.recording_time % 60
            time_text = f"{minutes:02d}:{seconds:02d}"
            
            # 暂停状态添加特殊样式
            if self.is_paused:
                self.time_label.setStyleSheet("""
                    QLabel {
                        color: #FFA500;
                        font-size: 12px;
                        font-weight: bold;
                        background-color: rgba(0, 0, 0, 120);
                        border-radius: 8px;
                        padding: 2px 6px;
                        margin-top: 2px;
                    }
                """)
                time_text += " (暂停)"
            else:
                self.time_label.setStyleSheet("""
                    QLabel {
                        color: white;
                        font-size: 12px;
                        font-weight: bold;
                        background-color: rgba(0, 0, 0, 80);
                        border-radius: 8px;
                        padding: 2px 6px;
                        margin-top: 2px;
                    }
                """)
            
            self.time_label.setText(time_text)
        else:
            self.time_label.setText("")
            self.time_label.setStyleSheet("""
                QLabel {
                    color: white;
                    font-size: 12px;
                    font-weight: bold;
                    background-color: rgba(0, 0, 0, 80);
                    border-radius: 8px;
                    padding: 2px 6px;
                    margin-top: 2px;
                }
            """)
    
    def set_recording_time(self, seconds):
        """设置录制时间"""
        self.recording_time = seconds
        self.update_time_display()
    
    def paintEvent(self, event):
        """自定义绘制事件"""
        super().paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        if self.pulse_animation and self.is_recording and not self.is_paused:
            # 绘制脉冲动画
            painter.setPen(Qt.NoPen)
            painter.setBrush(QColor(255, 255, 255, self.pulse_alpha))
            center = self.float_button.geometry().center()
            painter.drawEllipse(center, self.pulse_radius, self.pulse_radius)

    def on_pause_clicked(self):
        """暂停按钮点击事件"""
        if self.is_recording:
            if self.is_paused:
                self.resume_recording.emit()
            else:
                self.pause_recording.emit()
    
    def on_stop_clicked(self):
        """停止按钮点击事件"""
        if self.is_recording:
            self.stop_recording.emit()
    
    def set_recording_state(self, is_recording, is_paused=False):
        """设置录制状态"""
        self.is_recording = is_recording
        self.is_paused = is_paused
        self.update_button_icon()
    
    def on_float_button_clicked(self):
        """悬浮球按钮点击事件"""
        if self.is_recording:
            if self.is_paused:
                # 恢复录制
                self.is_paused = False
                self.update_button_icon()
                self.resume_recording.emit()
            else:
                # 暂停录制
                self.is_paused = True
                self.update_button_icon()
                self.pause_recording.emit()
        else:
            # 开始录制
            self.is_recording = True
            self.update_button_icon()
            self.start_recording.emit()
    
    def contextMenuEvent(self, event):
        """右键菜单事件"""
        menu = QMenu(self)
        
        if self.is_recording:
            stop_action = QAction("停止录制", self)
            stop_action.triggered.connect(self.on_stop_recording)
            menu.addAction(stop_action)
            
            if self.is_paused:
                resume_action = QAction("恢复录制", self)
                resume_action.triggered.connect(self.on_resume_recording)
                menu.addAction(resume_action)
            else:
                pause_action = QAction("暂停录制", self)
                pause_action.triggered.connect(self.on_pause_recording)
                menu.addAction(pause_action)
        else:
            start_action = QAction("开始录制", self)
            start_action.triggered.connect(self.on_start_recording)
            menu.addAction(start_action)
        
        menu.addSeparator()
        
        show_action = QAction("显示主窗口", self)
        show_action.triggered.connect(self.on_show_main_window)
        menu.addAction(show_action)
        
        menu.addSeparator()
        
        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.hide)
        menu.addAction(exit_action)
        
        menu.exec_(event.globalPos())
    
    def on_start_recording(self):
        """开始录制"""
        self.is_recording = True
        self.is_paused = False
        self.update_button_icon()
        self.start_recording.emit()
    
    def on_stop_recording(self):
        """停止录制"""
        self.is_recording = False
        self.is_paused = False
        self.update_button_icon()
        self.stop_recording.emit()
    
    def on_pause_recording(self):
        """暂停录制"""
        self.is_paused = True
        self.update_button_icon()
        self.pause_recording.emit()
    
    def on_resume_recording(self):
        """恢复录制"""
        self.is_paused = False
        self.update_button_icon()
        self.resume_recording.emit()
    
    def on_show_main_window(self):
        """显示主窗口"""
        self.show_main_window.emit()
    
    def setup_drag_behavior(self):
        """设置拖动行为"""
        self.drag_animation = QPropertyAnimation(self, b"pos")
        self.drag_animation.setEasingCurve(QEasingCurve.OutQuad)
        self.drag_animation.setDuration(100)  # 100ms动画
    
    def mousePressEvent(self, event):
        """鼠标按下事件"""
        if event.button() == Qt.LeftButton:
            self.drag_offset = event.pos()
            self.drag_animation.stop()
            event.accept()
    
    def mouseMoveEvent(self, event):
        """鼠标移动事件"""
        if event.buttons() == Qt.LeftButton:
            new_pos = event.globalPos() - self.drag_offset
            if self.drag_animation.state() == QPropertyAnimation.Running:
                self.drag_animation.setEndValue(new_pos)
            else:
                self.drag_animation.setStartValue(self.pos())
                self.drag_animation.setEndValue(new_pos)
                self.drag_animation.start()
            event.accept()
    
    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        if event.button() == Qt.LeftButton:
            event.accept()
            
    def setup_orbit_buttons(self):
        """设置环绕按钮"""
        # 暂停/继续按钮
        self.pause_btn = QPushButton("⏸", self)
        self.pause_btn.setFixedSize(30, 30)
        self.pause_btn.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 165, 0, 200);
                border-radius: 15px;
                border: 1px solid white;
                color: white;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: rgba(255, 165, 0, 255);
            }
        """)
        self.pause_btn.hide()
        self.pause_btn.clicked.connect(self.on_pause_clicked)
        
        # 停止按钮
        self.stop_btn = QPushButton("■", self)
        self.stop_btn.setFixedSize(30, 30)
        self.stop_btn.setStyleSheet("""
            QPushButton {
                background-color: rgba(220, 20, 60, 200);
                border-radius: 15px;
                border: 1px solid white;
                color: white;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: rgba(220, 20, 60, 255);
            }
        """)
        self.stop_btn.hide()
        self.stop_btn.clicked.connect(self.on_stop_clicked)
        
        self.orbit_buttons = [self.pause_btn, self.stop_btn]
    
    def enterEvent(self, event):
        """鼠标进入事件 - 显示半透明并启动环绕动画"""
        self.setWindowOpacity(0.9)
        self.hover_animation = True
        self.orbit_radius = 0
        for btn in self.orbit_buttons:
            btn.show()
        super().enterEvent(event)
        
    def leaveEvent(self, event):
        """鼠标离开事件 - 恢复透明度并停止环绕动画"""
        self.setWindowOpacity(0.7)
        self.hover_animation = False
        self.orbit_radius = 0
        for btn in self.orbit_buttons:
            btn.hide()
        self.update()  # 强制重绘
        super().leaveEvent(event)
        
    def showEvent(self, event):
        """显示事件 - 设置初始透明度"""
        self.setWindowOpacity(0.7)
        super().showEvent(event)
    
    def move_to_default_position(self):
        """移动到默认位置"""
        desktop = QApplication.desktop()
        screen_rect = desktop.screenGeometry()
        x = screen_rect.width() - self.width() - 20
        y = (screen_rect.height() - self.height()) // 2
        self.move(x, y)

# 导入QApplication
from PyQt5.QtWidgets import QApplication